import React, { useRef, Suspense, useState, useEffect, createRef, RefObject, useMemo } from 'react';
import { Canvas, useThree, useFrame } from '@react-three/fiber';
import { OrbitControls, PerspectiveCamera, Sphere, SpotLight, useTexture } from '@react-three/drei';
import { useSpring, animated } from '@react-spring/three';
// @ts-ignore
import { useDrag } from '@use-gesture/react';
import * as THREE from 'three'; // 导入 THREE
import gsap from 'gsap';

import { DNAModel } from '../components/DNAModel';
import { StarField } from '../components/StarField'; // 复用星空背景
import { TRNAModel, TRNAModelRef } from '../components/TRNAModel'; // 导入 TRNAModel 和 TRNAModelRef 类型
import { CodonTarget } from '../components/CodonTarget'; // 导入 CodonTarget
import { ProteinChain } from '../components/ProteinChain'; // 导入 ProteinChain
import { ParticleBurst } from '../components/ParticleBurst'; // 导入 ParticleBurst
import { checkMatch, getAminoAcid } from '../utils/matching'; // 导入配对逻辑和获取氨基酸函数
// 导入即将创建的组件
// import { ProteinChain } from '../components/ProteinChain';

// 添加雾气效果组件
const DynamicFog = () => {
  const fogRef = useRef<THREE.Fog>(null);
  
  useFrame(({ clock }) => {
    if (fogRef.current) {
      // 轻微调整雾气密度，创造呼吸效果
      const time = clock.getElapsedTime();
      const near = 15 + Math.sin(time * 0.2) * 2;
      const far = 30 + Math.sin(time * 0.1) * 3;
      fogRef.current.near = near;
      fogRef.current.far = far;
    }
  });

  return <fog ref={fogRef} attach="fog" args={['#0a0a20', 15, 30]} />;
};

// 添加细胞膜背景组件
interface CellMembraneProps {
  animated: boolean;
}

const CellMembrane = ({ animated }: CellMembraneProps) => {
  const sphereRef = useRef<THREE.Mesh>(null);
  
  useFrame(({ clock }) => {
    if (sphereRef.current && animated) {
      // 轻微旋转和呼吸效果，只在animated为true时执行
      const time = clock.getElapsedTime();
      sphereRef.current.rotation.y = time * 0.05;
      sphereRef.current.rotation.x = Math.sin(time * 0.1) * 0.05;
      // 轻微缩放
      const scale = 1 + Math.sin(time * 0.2) * 0.02;
      sphereRef.current.scale.set(scale, scale, scale);
    }
  });

  return (
    <Sphere ref={sphereRef} args={[25, 32, 32]} position={[0, 0, -20]}>
      <meshBasicMaterial 
        color="#1a5f7a" 
        transparent={true} 
        opacity={0.15} 
        side={THREE.BackSide}
        wireframe={true}
      />
    </Sphere>
  );
};

// 创建聚焦光效果组件
const FocusLights = () => {
  return (
    <>
      {/* mRNA区域聚焦光 */}
      <SpotLight
        position={[0, 12, 8]}
        angle={0.4}
        penumbra={0.6}
        intensity={4.5}
        color="#4da6ff"
        distance={40}
        castShadow
        target-position={[0, 2, 0]}
      />
      
      {/* tRNA区域聚焦光 */}
      <SpotLight
        position={[5, -2, 8]}
        angle={0.5}
        penumbra={0.5}
        intensity={1.8}
        color="#66ff99"
        distance={20}
        castShadow
        target-position={[5, -5, 0]}
      />
    </>
  );
};

// 创建一个内部组件来处理 Three.js 相关的逻辑
interface DNASceneProps {
  showFog: boolean;
  showMembrane: boolean;
  showSpotlights: boolean;
  showParticles: boolean;
  membraneAnimated: boolean;
  showStars: boolean;
  starsAnimated: boolean;
  showDNAModel: boolean;
  showMatchAreas: boolean;
  // 添加消息提示函数
  setMessage: (message: {text: string, type: 'success' | 'error' | 'info' | null}) => void;
}

// 匹配区域指示器组件
const MatchArea = ({ position, radius, isPaired }: { position: [number, number, number], radius: number, isPaired: boolean }) => {
  const color = isPaired ? "#666666" : "#00ff00";
  return (
    <mesh position={position} rotation={[-Math.PI / 2, 0, 0]}>
      <ringGeometry args={[radius - 0.05, radius, 32]} />
      <meshBasicMaterial color={color} transparent opacity={0.3} />
      
      {/* 添加水平指示线，表明只考虑水平距离 */}
      <lineSegments>
        <edgesGeometry attach="geometry">
          <boxGeometry args={[radius * 2, 0.05, 0.05]} />
        </edgesGeometry>
        <lineBasicMaterial attach="material" color={color} />
      </lineSegments>
    </mesh>
  );
};

const DNAScene = ({ 
  showFog, 
  showMembrane, 
  showSpotlights, 
  showParticles, 
  membraneAnimated,
  showStars,
  starsAnimated,
  showDNAModel,
  showMatchAreas,
  // 添加消息提示函数
  setMessage
}: DNASceneProps) => {
  const { scene, camera, gl } = useThree();
  const canvasContainerRef = useRef<HTMLDivElement>(null);
  const controlsRef = useRef<any>(null);
  const [isDragging, setIsDragging] = useState(false);
  // 跟踪当前正在拖动的tRNA索引，-1表示没有拖动
  const [currentDraggingIndex, setCurrentDraggingIndex] = useState<number>(-1);
  // 匹配区域可视化配置
  const matchAreaRadius = 2.0; // 与水平匹配阈值保持一致

  // 游戏状态：mRNA 序列，使用一些示例密码子
  const [mRNASequence, setMRNASequence] = useState<string[]>(['AUG', 'CGC', 'GUA', 'UAA']);
  // 游戏状态：已配对的密码子索引，用于避免重复配对
  const [pairedCodons, setPairedCodons] = useState<number[]>([]);
  // 游戏状态：合成的蛋白质链 (存储氨基酸缩写)
  const [proteinChain, setProteinChain] = useState<string[]>([]);
  // 游戏状态：可用的 tRNA 模型列表 (这里可以存储 tRNA 的类型或反密码子)
  const [availableTRNAs, setAvailableTRNAs] = useState<string[]>([
    'UAC', // 对应 AUG
    'GCG', // 对应 CGC
    'CAU', // 对应 GUA
    // 添加一些额外的 tRNA
    'ACU', 'UGA', 'CUG'
  ]);
  // 游戏状态：活跃的粒子爆发效果列表
  const [particleBursts, setParticleBursts] = useState<{ id: number, position: [number, number, number] }[]>([]);
  // 用于生成粒子爆发唯一 ID
  const particleBurstId = useRef(0);

  // 创建一个 ref 数组来存储每个 TRNAModel 实例的引用 (RefObject 类型)
  const trnaRefs = useRef<(RefObject<TRNAModelRef | null>)[]>([]);

  // 当 availableTRNAs 列表变化时，更新 ref 数组的大小并创建新的 RefObject
  useEffect(() => {
    trnaRefs.current = availableTRNAs.map((_, i) => trnaRefs.current[i] ?? createRef<TRNAModelRef | null>());
  }, [availableTRNAs]);

  // 计算 mRNA 密码子在 3D 空间中的位置
  const codonPositions = mRNASequence.map((_, index) => {
    // 沿着 X 轴水平排列密码子，留出间隔
    const x = (index - mRNASequence.length / 2 + 0.5) * 2; // 中心对齐，间隔为 2
    const y = 2; // 放置在 Canvas 中上方
    const z = 0; // 放置在中间层
    return [x, y, z] as [number, number, number];
  });

  // 计算 tRNA 模型在右下角区域的位置
  const trnaPositions = availableTRNAs.map((_, index) => {
    // 简单示例：在右下角区域内随机或网格排列
    const x = 5 + (index % 3) * 2; // 示例布局
    const y = -5 - Math.floor(index / 3) * 2; // 示例布局
    const z = 0.5; // 放置在靠前一点的层，便于拖拽
    return [x, y, z] as [number, number, number];
  });

  // Raycaster 用于碰撞检测
  const raycaster = new THREE.Raycaster();
  const mouse = new THREE.Vector2();

  // 处理 tRNA 拖拽开始事件
  const handleTRNADragStart = (trnaIndex: number) => {
    // 如果已经有正在拖动的tRNA，则忽略此次拖动尝试
    if (currentDraggingIndex !== -1) {
      return;
    }
    
    // 设置当前正在拖动的tRNA索引
    setCurrentDraggingIndex(trnaIndex);
    
    // 禁用相机控制
    setIsDragging(true);
    if (controlsRef.current) {
      // 存储当前相机位置，以便后续恢复
      const currentCameraPosition = camera.position.clone();
      const currentCameraRotation = camera.rotation.clone();
      
      // 在对象上保存当前相机状态
      controlsRef.current.userData = {
        ...controlsRef.current.userData,
        savedPosition: currentCameraPosition,
        savedRotation: currentCameraRotation
      };
      
      // 禁用控制器
      controlsRef.current.enabled = false;
      
      // 平滑地将相机移动到正视图位置（初始加载位置）
      gsap.to(camera.position, {
        x: 0,
        y: 0,
        z: 15,
        duration: 0.5,
        ease: "power2.out"
      });
      
      // 设置相机方向朝向场景中心
      camera.lookAt(0, 0, 0);
    }
  };

  // 处理 tRNA 拖拽释放事件
  const handleTRNADrop = (currentPosition: [number, number, number], anticodon: string, trnaIndex: number) => {
    console.log(`tRNA ${anticodon} dropped at`, currentPosition);

    // 重新启用相机控制
    setIsDragging(false);
    if (controlsRef.current) {
      // 恢复相机位置，如果有保存的状态
      if (controlsRef.current.userData?.savedPosition && controlsRef.current.userData?.savedRotation) {
        // 平滑地恢复相机位置
        gsap.to(camera.position, {
          x: controlsRef.current.userData.savedPosition.x,
          y: controlsRef.current.userData.savedPosition.y,
          z: controlsRef.current.userData.savedPosition.z,
          duration: 0.5,
          ease: "power2.out",
          onComplete: () => {
            // 恢复相机旋转
            camera.rotation.copy(controlsRef.current.userData.savedRotation);
            // 重新启用控制器
            controlsRef.current.enabled = true;
          }
        });
      } else {
        // 如果没有保存的状态，直接启用控制器
        controlsRef.current.enabled = true;
      }
    }
    
    // 重置当前拖动索引
    setCurrentDraggingIndex(-1);

    // 获取 Canvas 的 DOM 元素及其边界
    const canvas = gl.domElement; // 使用 gl.domElement 获取 Canvas DOM 元素
    const canvasBounds = canvas.getBoundingClientRect();

    // 直接使用场景坐标计算位置，避免复杂的屏幕坐标转换
    // 简化检测逻辑：检查tRNA是否足够接近任何一个密码子
    let matchFound = false;
    let matchedCodonIndex = -1;
    
    // 打印所有mRNA密码子位置，帮助调试
    console.log("所有mRNA密码子位置:", codonPositions);
    console.log("当前tRNA位置:", currentPosition);

    // 在正视图下的距离计算
    // 遍历所有mRNA密码子位置
    for (let i = 0; i < mRNASequence.length; i++) {
      // 如果该密码子已经配对，则跳过
      if (pairedCodons.includes(i)) {
        continue;
      }

      // 主要考虑水平(X轴)距离，因为Y轴差距太大
      const dx = currentPosition[0] - codonPositions[i][0];
      
      // 计算水平距离
      const horizontalDistance = Math.abs(dx);
      
      // 调整匹配阈值 - 只考虑水平距离
      const matchThreshold = 2.0; // 合理的水平距离阈值
      
      // 打印每个密码子的距离计算，帮助调试
      console.log(`密码子${i} (${mRNASequence[i]}): dx=${dx.toFixed(2)}, 水平距离=${horizontalDistance.toFixed(2)}, 阈值=${matchThreshold}`);
      
      if (horizontalDistance < matchThreshold) {
        matchFound = true;
        matchedCodonIndex = i;
        
        // 记录调试信息
        console.log(`找到匹配! 密码子${i} (${mRNASequence[i]}): 水平距离=${horizontalDistance.toFixed(2)}, 阈值=${matchThreshold}`);
        break;
      }
    }

    if (matchFound && matchedCodonIndex !== -1) {
      const targetCodon = mRNASequence[matchedCodonIndex];
      console.log(`Dropped near codon ${targetCodon} at index ${matchedCodonIndex}`);

      // 检查配对是否正确
      if (checkMatch(anticodon, targetCodon)) {
        console.log('Match successful!');
        
        // 打印详细信息，帮助调试
        console.log(`Anticodon: ${anticodon}, Codon: ${targetCodon}`);
        console.log(`Match details:`, 
          { 
            A_matches_U: anticodon.includes('A') && targetCodon.includes('U'),
            U_matches_A: anticodon.includes('U') && targetCodon.includes('A'),
            G_matches_C: anticodon.includes('G') && targetCodon.includes('C'),
            C_matches_G: anticodon.includes('C') && targetCodon.includes('G')
          }
        );
        
        // 触发配对成功动画 (闪光 / 粒子)
        setParticleBursts(prev => [...prev, { id: particleBurstId.current++, position: codonPositions[matchedCodonIndex] }]);

        // 获取对应的氨基酸并更新蛋白质链
        const aminoAcid = getAminoAcid(targetCodon);
        if (aminoAcid && aminoAcid !== 'Stop') { // 忽略终止密码子
          setProteinChain(prev => [...prev, aminoAcid]);
        }

        // 标记该密码子为已配对
        setPairedCodons(prev => [...prev, matchedCodonIndex]);

        // 显示成功提示
        setMessage({ text: `成功匹配! ${targetCodon}(密码子) 与 ${anticodon}(反密码子) 配对，形成氨基酸: ${aminoAcid || '未知'}`, type: 'success' });
      } else {
        console.log('Match failed.');
        console.log(`Anticodon: ${anticodon}, Codon: ${targetCodon}`);
        // 触发 tRNA 弹回原位动画
        trnaRefs.current[trnaIndex]?.current?.returnToInitialPosition();
        
        // 显示失败提示
        setMessage({ text: `配对失败! ${anticodon}(反密码子) 无法与 ${targetCodon}(密码子) 配对。`, type: 'error' });
      }
    } else {
      console.log('No matching codon found nearby.');
      // 触发 tRNA 弹回原位动画
      trnaRefs.current[trnaIndex]?.current?.returnToInitialPosition();
    }
  };

  // 处理粒子动画结束事件
  const handleParticleAnimationEnd = (id: number) => {
    // 使用函数式更新确保状态更新正确
    setParticleBursts(prev => prev.filter(burst => burst.id !== id));
  };

  // 确保粒子效果不会累积过多
  useEffect(() => {
    // 如果粒子效果超过5个，清理最早的
    if (particleBursts.length > 5) {
      setParticleBursts(prev => prev.slice(-5));
    }
  }, [particleBursts]);

  // 在渲染 CodonTarget 时，添加 userData 以便后续识别和获取信息，并传递 isPaired 状态
  const renderCodonTargets = () => {
    return mRNASequence.map((codon, index) => (
      <group key={index}>
        <CodonTarget
          position={codonPositions[index]}
          codon={codon}
          isPaired={pairedCodons.includes(index)} // 根据 pairedCodons 状态设置 isPaired
          // 添加 userData，存储密码子索引
          userData={{ isCodonTarget: true, codonIndex: index }}
        />
        {/* 在拖拽时或一直显示匹配区域，提供视觉反馈 */}
        {showMatchAreas && (
          <MatchArea 
            position={[codonPositions[index][0], codonPositions[index][1], codonPositions[index][2] - 0.3]} 
            radius={matchAreaRadius}
            isPaired={pairedCodons.includes(index)}
          />
        )}
      </group>
    ));
  };
  
  // 在渲染 TRNAModel 时，传递 onDrop 回调和其自身的索引，并绑定 ref
  const renderTRNAModels = () => {
    return availableTRNAs.map((anticodon, index) => (
      <TRNAModel 
        key={index} 
        ref={trnaRefs.current[index]} // 绑定 ref
        modelPath="/assets/models/tRNA.glb" // 使用同一个示例模型，后续修改
        initialPosition={trnaPositions[index]} // 传递初始位置
        anticodon={anticodon} // 传递反密码子信息
        // 修改 onDrop 回调，不再传递弹回动画回调，直接在 handleTRNADrop 中的 ref 调用
        onDrop={(currentPosition, droppedAnticodon) => handleTRNADrop(currentPosition, droppedAnticodon, index)} 
        onDragStart={() => handleTRNADragStart(index)} // 添加拖拽开始回调
        canDrag={currentDraggingIndex === -1 || currentDraggingIndex === index} // 只有在没有拖动或当前是自己在拖动时才允许拖动
       />
    ));
  };

  return (
    <>
      {/* 根据showFog属性决定是否显示动态雾气 */}
      {showFog && <DynamicFog />}
      
      {/* 基础光照 */}
      <ambientLight intensity={0.3} /> {/* 降低环境光强度，让聚焦光更明显 */}
      <pointLight position={[10, 10, 10]} intensity={0.8} />
      
      {/* 添加聚焦光效果 */}
      {showSpotlights && <FocusLights />}
      
      <Suspense fallback={null}>
        {/* 添加细胞膜背景 */}
        {showMembrane && <CellMembrane animated={membraneAnimated} />}
        
        {/* 星空背景 */}
        {showStars && <AnimatableStarField animated={starsAnimated} />}
        
        {/* DNA模型 */}
        {showDNAModel && <DNAModel position={[0, 5, -10]} scale={[1, 1, 1]} />}
        
        {/* 游戏元素 */}
        {renderCodonTargets()}
        {renderTRNAModels()}
        <ProteinChain aminoAcids={proteinChain} position={[-5, -3, 0]} />
        
        {/* 粒子效果 */}
        {showParticles && particleBursts.map(burst => (
          <ParticleBurst 
            key={burst.id} 
            position={burst.position} 
            onAnimationEnd={() => handleParticleAnimationEnd(burst.id)} 
          />
        ))}
      </Suspense>
      
      {/* 相机控制，根据拖拽状态启用/禁用 */}
      <OrbitControls 
        ref={controlsRef}
        enableZoom={true} 
        enablePan={true} 
        enableRotate={true}
        enabled={!isDragging} // 根据拖拽状态启用/禁用
      />
    </>
  );
};

// 添加加载状态指示器组件
const LoadingIndicator = () => (
  <div style={{
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    color: 'white',
    fontSize: '1.5rem',
    textAlign: 'center',
    zIndex: 20,
    pointerEvents: 'none'
  }}>
    <div>加载模型中...</div>
    <div style={{ marginTop: '1rem' }}>
      <div style={{
        width: '50px',
        height: '50px',
        border: '3px solid #f3f3f3',
        borderTop: '3px solid #3498db',
        borderRadius: '50%',
        animation: 'spin 1s linear infinite',
        margin: '0 auto'
      }} />
    </div>
  </div>
);

// 创建一个修改版的StarField组件，支持动画控制
interface StarFieldProps {
  animated: boolean;
}

const AnimatableStarField = ({ animated }: StarFieldProps) => {
  const starsRef = useRef<THREE.Points>(null);
  
  useFrame((state, delta) => {
    if (starsRef.current && animated) {
      // 只在animated为true时旋转星空
      starsRef.current.rotation.y += delta * 0.05;
    }
  });

  // 生成随机星星位置
  const starCount = 2000;
  const positions = useMemo(() => {
    const pos = new Float32Array(starCount * 3);
    for (let i = 0; i < starCount; i++) {
      const i3 = i * 3;
      pos[i3] = (Math.random() - 0.5) * 100;
      pos[i3 + 1] = (Math.random() - 0.5) * 100;
      pos[i3 + 2] = (Math.random() - 0.5) * 100;
    }
    return pos;
  }, []);

  return (
    <points ref={starsRef}>
      <bufferGeometry>
        <bufferAttribute
          attach="attributes-position"
          count={starCount}
          array={positions}
          itemSize={3}
          args={[positions, 3]}
        />
      </bufferGeometry>
      <pointsMaterial
        size={0.1}
        color="#ffffff"
        transparent
        opacity={0.8}
        sizeAttenuation
      />
    </points>
  );
};

// 消息提示组件
const MessageToast = ({ message, type, onClose }: { 
  message: string, 
  type: 'success' | 'error' | 'info' | null,
  onClose: () => void 
}) => {
  useEffect(() => {
    if (message && type) {
      const timer = setTimeout(() => {
        onClose();
      }, 3000); // 3秒后自动关闭
      
      return () => clearTimeout(timer);
    }
  }, [message, type, onClose]);
  
  if (!message || !type) return null;
  
  const bgColor = type === 'success' ? 'rgba(76, 175, 80, 0.9)' : 
                  type === 'error' ? 'rgba(244, 67, 54, 0.9)' : 
                  'rgba(33, 150, 243, 0.9)';
  
  return (
    <div style={{
      position: 'absolute',
      top: '20px',
      left: '50%',
      transform: 'translateX(-50%)',
      backgroundColor: bgColor,
      color: 'white',
      padding: '10px 20px',
      borderRadius: '4px',
      zIndex: 1000,
      boxShadow: '0 2px 10px rgba(0,0,0,0.2)',
      maxWidth: '80%',
      textAlign: 'center',
      pointerEvents: 'auto'
    }}>
      {message}
    </div>
  );
};

// 主组件
const DNA = () => {
  const [isLoading, setIsLoading] = useState(true);
  // 添加消息提示状态
  const [message, setMessage] = useState<{text: string, type: 'success' | 'error' | 'info' | null}>({
    text: '',
    type: null
  });
  
  // 从localStorage加载用户设置，如果没有则使用默认值
  const loadSetting = (key: string, defaultValue: boolean): boolean => {
    const savedValue = localStorage.getItem(`dna_setting_${key}`);
    return savedValue !== null ? savedValue === 'true' : defaultValue;
  };
  
  // 初始化状态，加载保存的用户偏好
  const [showFog, setShowFog] = useState(() => loadSetting('showFog', true));
  const [showMembrane, setShowMembrane] = useState(() => loadSetting('showMembrane', true));
  const [showSpotlights, setShowSpotlights] = useState(() => loadSetting('showSpotlights', true));
  const [showParticles, setShowParticles] = useState(() => loadSetting('showParticles', true));
  const [membraneAnimated, setMembraneAnimated] = useState(() => loadSetting('membraneAnimated', true));
  const [showStars, setShowStars] = useState(() => loadSetting('showStars', true));
  const [starsAnimated, setStarsAnimated] = useState(() => loadSetting('starsAnimated', true));
  const [showDNAModel, setShowDNAModel] = useState(() => loadSetting('showDNAModel', true));
  const [controlPanelExpanded, setControlPanelExpanded] = useState(() => loadSetting('controlPanelExpanded', false));
  const [showMatchAreas, setShowMatchAreas] = useState(() => loadSetting('showMatchAreas', true)); // 添加匹配区域控制

  // 使用 useEffect 来监听加载状态
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 2000); // 给模型加载一些时间

    return () => clearTimeout(timer);
  }, []);
  
  // 保存设置到localStorage
  const saveSetting = (key: string, value: boolean) => {
    localStorage.setItem(`dna_setting_${key}`, String(value));
  };

  // 切换各种效果并保存设置
  const toggleFog = () => {
    const newValue = !showFog;
    setShowFog(newValue);
    saveSetting('showFog', newValue);
  };
  
  const toggleMembrane = () => {
    const newValue = !showMembrane;
    setShowMembrane(newValue);
    saveSetting('showMembrane', newValue);
  };
  
  const toggleSpotlights = () => {
    const newValue = !showSpotlights;
    setShowSpotlights(newValue);
    saveSetting('showSpotlights', newValue);
  };
  
  const toggleParticles = () => {
    const newValue = !showParticles;
    setShowParticles(newValue);
    saveSetting('showParticles', newValue);
  };
  
  const toggleMembraneAnimation = () => {
    const newValue = !membraneAnimated;
    setMembraneAnimated(newValue);
    saveSetting('membraneAnimated', newValue);
  };
  
  const toggleStars = () => {
    const newValue = !showStars;
    setShowStars(newValue);
    saveSetting('showStars', newValue);
  };
  
  const toggleStarsAnimation = () => {
    const newValue = !starsAnimated;
    setStarsAnimated(newValue);
    saveSetting('starsAnimated', newValue);
  };
  
  const toggleDNAModel = () => {
    const newValue = !showDNAModel;
    setShowDNAModel(newValue);
    saveSetting('showDNAModel', newValue);
  };
  
  const toggleMatchAreas = () => {
    const newValue = !showMatchAreas;
    setShowMatchAreas(newValue);
    saveSetting('showMatchAreas', newValue);
  };
  
  const toggleControlPanel = () => {
    const newValue = !controlPanelExpanded;
    setControlPanelExpanded(newValue);
    saveSetting('controlPanelExpanded', newValue);
  };
  
  // 重置所有设置为默认值
  const resetSettings = () => {
    setShowFog(true);
    setShowMembrane(true);
    setShowSpotlights(true);
    setShowParticles(true);
    setMembraneAnimated(true);
    setShowStars(true);
    setStarsAnimated(true);
    setShowDNAModel(true);
    
    // 保存默认设置
    saveSetting('showFog', true);
    saveSetting('showMembrane', true);
    saveSetting('showSpotlights', true);
    saveSetting('showParticles', true);
    saveSetting('membraneAnimated', true);
    saveSetting('showStars', true);
    saveSetting('starsAnimated', true);
    saveSetting('showDNAModel', true);
  };

  return (
    <div className="dna-game-page" style={{ position: 'relative', width: '100vw', height: '100vh', overflow: 'hidden' }}>
      <Canvas
        camera={{ position: [0, 0, 15], fov: 75 }}
        style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', background: '#1a1a2e' }}
      >
        <Suspense fallback={null}>
          <DNAScene 
            showFog={showFog} 
            showMembrane={showMembrane}
            showSpotlights={showSpotlights}
            showParticles={showParticles}
            membraneAnimated={membraneAnimated}
            showStars={showStars}
            starsAnimated={starsAnimated}
            showDNAModel={showDNAModel}
            showMatchAreas={showMatchAreas}
            // 添加消息提示函数
            setMessage={setMessage}
          />
        </Suspense>
      </Canvas>

      {isLoading && <LoadingIndicator />}

      <div className="ui-overlay" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10, pointerEvents: 'none' }}>
        {/* tRNA区域提示 */}
        <div style={{ 
          position: 'absolute',
          bottom: '20px',
          right: '20px',
          width: '250px',
          height: '250px',
          border: '2px dashed rgba(255, 255, 255, 0.5)',
          color: 'rgba(255, 255, 255, 0.8)',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          pointerEvents: 'auto',
          borderRadius: '10px',
          padding: '10px'
        }}>
          可用 tRNA (拖拽到 mRNA)
        </div>
        
        {/* 控制面板 */}
        <div style={{
          position: 'absolute',
          bottom: '20px',
          left: '20px',
          background: 'rgba(0, 0, 0, 0.7)',
          padding: '15px',
          borderRadius: '8px',
          pointerEvents: 'auto',
          display: 'flex',
          flexDirection: 'column',
          gap: '8px',
          boxShadow: '0 0 10px rgba(0,0,0,0.5)',
          maxWidth: '200px',
          transition: 'all 0.3s ease'
        }}>
          {/* 控制面板标题和折叠按钮 */}
          <div 
            style={{ 
              color: 'white', 
              fontSize: '16px', 
              marginBottom: '5px', 
              borderBottom: '1px solid rgba(255,255,255,0.3)', 
              paddingBottom: '5px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              cursor: 'pointer'
            }}
            onClick={toggleControlPanel}
          >
            <span>视觉效果控制</span>
            <span style={{ transform: controlPanelExpanded ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.3s ease' }}>
              ▼
            </span>
          </div>
          
          {/* 可折叠的控制项 */}
          <div style={{ 
            maxHeight: controlPanelExpanded ? '500px' : '0',
            overflow: 'hidden',
            transition: 'max-height 0.3s ease',
            display: 'flex',
            flexDirection: 'column',
            gap: '8px'
          }}>
            <ControlButton 
              onClick={toggleFog}
              active={showFog}
              label="雾气效果"
            />
            
            <ControlButton 
              onClick={toggleMembrane}
              active={showMembrane}
              label="细胞膜背景"
            />
            
            {showMembrane && (
              <ControlButton 
                onClick={toggleMembraneAnimation}
                active={membraneAnimated}
                label="膜动画效果"
                indent={true}
              />
            )}
            
            <ControlButton 
              onClick={toggleSpotlights}
              active={showSpotlights}
              label="聚光灯效果"
            />
            
            <ControlButton 
              onClick={toggleParticles}
              active={showParticles}
              label="粒子效果"
            />
            
            <ControlButton 
              onClick={toggleStars}
              active={showStars}
              label="星空效果"
            />
            
            {showStars && (
              <ControlButton 
                onClick={toggleStarsAnimation}
                active={starsAnimated}
                label="星空动画效果"
                indent={true}
              />
            )}
            
            <ControlButton 
              onClick={toggleDNAModel}
              active={showDNAModel}
              label="DNA模型效果"
            />
            
            <ControlButton 
              onClick={toggleMatchAreas}
              active={showMatchAreas}
              label="匹配区域指示"
            />
            
            {/* 分隔线 */}
            <div style={{ 
              height: '1px', 
              background: 'rgba(255,255,255,0.2)', 
              margin: '5px 0' 
            }} />
            
            {/* 重置按钮 */}
            <button
              onClick={resetSettings}
              style={{
                background: '#007bff',
                color: 'white',
                border: 'none',
                padding: '8px 10px',
                borderRadius: '4px',
                cursor: 'pointer',
                fontSize: '14px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '5px',
                transition: 'all 0.2s ease'
              }}
            >
              <span style={{ fontSize: '12px' }}>↻</span>
              恢复默认设置
            </button>
          </div>
        </div>
      </div>

      {message.text && <MessageToast message={message.text} type={message.type} onClose={() => setMessage({ text: '', type: null })} />}
    </div>
  );
};

// 控制按钮组件
interface ControlButtonProps {
  onClick: () => void;
  active: boolean;
  label: string;
  indent?: boolean;
}

const ControlButton = ({ onClick, active, label, indent = false }: ControlButtonProps) => (
  <button 
    onClick={onClick}
    style={{
      background: active ? '#4CAF50' : '#f44336',
      color: 'white',
      border: 'none',
      padding: '5px 10px',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px',
      textAlign: 'left',
      marginLeft: indent ? '10px' : '0',
      transition: 'all 0.2s ease',
      display: 'flex',
      alignItems: 'center',
      width: '100%'
    }}
  >
    <div style={{ 
      width: '10px', 
      height: '10px', 
      borderRadius: '50%', 
      background: active ? '#4CAF50' : '#f44336',
      marginRight: '8px',
      boxShadow: active ? '0 0 5px #4CAF50' : 'none',
      border: '1px solid white'
    }}></div>
    {label}
  </button>
);

// 添加全局样式
const style = document.createElement('style');
style.textContent = `
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;
document.head.appendChild(style);

export default DNA; 